<template>
	<view class="input-select">
		<view class="input-select-bd" @click="handleClick">
			<input
				class="input-inner"
				:style="{ fontSize: $g.addUnit(size) }"
				:value="selectedLabel"
				:placeholder="placeholder"
			/>
			<text v-if="!disabled" class="iconfont input-icon" :class="'icon-'+iconType+'-down'" :style="{ color: iconColor }"></text>
		</view>
		<pys-select ref="select" :list="list"/>
	</view>
</template>

<script>
import pysSelect from '../pys-select/pys-select.vue';

export default {
	name: 'inputSelect',
	components: {
		pysSelect
	},
	props: {
		placeholder: {
			type: String,
			default: ''
		},
		disabled: {
			type: Boolean,
			default: false
		},
		list: {
			type: Array,
			default() {
				return [];
			}
		},
		value: {
			type: [Number, String]
		},
		iconType: {
			type: String,
			default: 'caret'
		},
		iconColor: {
			type: String,
			default: '#aaa'
		},
		size: {
			type: [String, Number],
			default: '28'
		}
	},
	watch: {
		value(val) {
			if (!(val === this.selectedValue)) {
				this.setValue(val);
			}
		},
		list() {
			if (this.value && this.value !== this.selectedValue) {
				this.setValue(this.value);
			}
		}
	},
	data() {
		return {
			selectedLabel: '',
			selectedValue: this.value || '',
		};
	},
	methods: {
		handleClick() {
			if (this.disabled) return;
			this.$refs['select'].open()
				.then(res => {
					this.selectedLabel = res.label;
					this.selectedValue = res.value;
					this.$emit('input', res.value);
				});
		},
		setValue(value) {
			const item = this.list.find(e => e.value == value);
			if (item && item.value) {
				this.selectedValue = item.value;
				this.selectedLabel = item.label;
				this.$refs['select'].setValue(item.value);
			}
		},
	},
	mounted() {
		if(this.value && this.list) {
			this.setValue(this.value);
		}
	}
};
</script>

<style lang="scss" scoped>
.input-select {
	height: 100%;
	width: 100%;
}
.input-select-bd {
	height: 100%;
	width: 100%;
	display: flex;
	align-items: center;
	padding-right: 16rpx;
	
	.input-inner {
		flex: 1 0 1%;
	}
	
	.iconfont {
		margin-left: 16rpx;
		font-size: 24rpx;
		color: #aaa;
	}
}

</style>
